package models

import (
	"errors"
	"gorm.io/gorm"
)

type Project struct {
	Id      int
	UserId  int
	Name    string
	Path    string
	Address string
	Version int
	Public  int
	Looknum int
}

type History struct {
	Id         int
	Project_id int
	User_id    int
	Name       string
	Path       string
	Version    int
	Ms         string
	CommitId   int
}
type File struct {
	Id         int
	Project_id int
	User_id    int
	Name       string
	Path       string
	Version    int
}

func (Project) TableName() string {
	return "project"
}
func (History) TableName() string {
	return "history"
}
func GetProject() ([]Project, error, *gorm.DB) {
	var p []Project
	tx := db.Begin()
	res := tx.Find(&p)
	if res.RowsAffected < 1 {
		tx.Rollback() //错误回滚
		return []Project{}, errors.New("查询失败"), nil
	}
	tx.Commit() //成功提交
	return p, nil, tx
}
func Create(h History) error {
	res := db.Create(&h)
	if res.RowsAffected <= 1 {
		return errors.New("添加失败")
	}
	return nil
}
func CreateFile(h File) error {
	res := db.Create(&h)
	if res.RowsAffected <= 1 {
		return errors.New("添加失败")
	}
	return nil
}

// 根据历史版本查询数据
func GetPath(version int) (History, error) {
	var h History
	res := db.Table("history").Where("version=?", version).First(&h)
	if res.RowsAffected < 1 {
		return History{}, errors.New("查询失败")
	}
	return h, nil
}

// 当前状态修改为回滚的对应状态
func UpdateFile(id int, path string) error {
	res := db.Table("file").Where("id=?", id).Update("path", path)
	if res.RowsAffected < 1 {
		return errors.New("修改成功")
	}
	return nil
}

// 支持commit id和提交描述进行多条件搜索
func GetData(id int, ms string) ([]History, error) {
	var h []History
	res := db.Table("history").Where("commitId =? and ms =?", id, ms).Find(&h)
	if res.RowsAffected < 1 {
		return []History{}, errors.New("查询失败")
	}
	return h, nil
}

// 修改仓库名
func UpdateProject(name string, id int) error {
	res := db.Table("project").Where("id=?", id).Update("name", name)
	if res.RowsAffected < 1 {
		return errors.New("修改成功")
	}
	return nil
}
